﻿using System;
using Timer = System.Timers.Timer;
using System.Web;
using umbraco.DataLayer;

namespace Designit.Umb.Newsletter.Bll
{
    class DelayedSend : IHttpModule
    {
        private Timer timer;
        private static bool HasAppStarted = false;
        private readonly static object _syncObject = new object();
        public void Init(HttpApplication application)
        {
            //workaround to avoid 3 x call 
            if (!HasAppStarted)
            {
                lock (_syncObject)
                {
                    if (!HasAppStarted)
                    {
                        timer = new Timer(600000);
                        timer.Elapsed += timer_Elapsed;
                        timer.Start();
                        HasAppStarted = true;

                    }
                }
            }
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            try
            {
                timer.Stop();
                run();
            }
            finally
            {
                timer.Start();


            }
        }
        private void run()
        {

            DateTime datetime;

            datetime = DateTime.UtcNow;
            using (var reader =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader(
                    "select * from newsLetterCampaignDelayedSend"))
            {
                while (reader.Read())
                {

                    DateTime localCampTime = DateTime.Parse(reader.GetString("timeStamp"));
                    DateTime temp = datetime;
                    double hours = Int32.Parse(reader.GetString("timezone"));
                    temp = temp.AddHours(hours);
                    if (temp >= localCampTime)
                    {
                        EmbedNewsletter.SendCampaign(reader.GetInt("campaignId"));
                        umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery(
                            "delete from newsLetterCampaignDelayedSend where id=@id",
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", reader.GetInt("id")));
                    }
                }
            }

            timer.Interval = (1800 * 1000);

        }


        public void Dispose()
        {

        }
    }
}
